#!/bin/bash

# 检查是否提供了仓库地址
if [ $# -eq 0 ]; then
    echo "用法: $0 <gitee仓库地址>"
    echo "示例: $0 git@gitee.com:lsyhahaha/ac-wing-project.git"
    exit 1
fi

REPO_URL=$1
REPO_NAME=$(basename "$REPO_URL" .git)

# 1. 检查是否已添加gitee.com到known_hosts
if ! ssh-keygen -F gitee.com > /dev/null; then
    echo "将Gitee的SSH主机密钥添加到known_hosts..."
    ssh-keyscan gitee.com >> ~/.ssh/known_hosts 2>/dev/null
    
    # 验证是否添加成功
    if ! ssh-keygen -F gitee.com > /dev/null; then
        echo "错误: 无法添加Gitee主机密钥"
        exit 1
    fi
fi

# 2. 测试SSH连接
echo "测试SSH连接到Gitee..."
if ! ssh -T git@gitee.com 2>&1 | grep -q "authenticated"; then
    echo "错误: SSH验证失败"
    echo "请确保:"
    echo "1. 你已生成SSH密钥"
    echo "2. 公钥已添加到Gitee账户"
    echo "你可以运行以下命令生成SSH密钥:"
    echo "  ssh-keygen -t ed25519 -C \"your_email@example.com\""
    echo "然后查看公钥并添加到Gitee:"
    echo "  cat ~/.ssh/id_ed25519.pub"
    exit 1
fi

# 3. 克隆仓库
echo "正在克隆仓库 $REPO_URL..."
if git clone "$REPO_URL"; then
    echo "成功克隆仓库到 $REPO_NAME 目录"
else
    echo "错误: 克隆仓库失败"
    echo "请检查:"
    echo "1. 仓库地址是否正确"
    echo "2. 你有访问该仓库的权限"
    exit 1
fi